package com.gaogzhen.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.gaogzhen.utils.WebLog;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Administrator
 */
@Component
@Aspect
@Order(1)
@Slf4j
public class WebLogAspect {

    /**
     * 日志记录：
     *  环绕通知：方法执行前后
     */

    /**
     * 切入点
     */
    @Pointcut("execution(* com.gaogzhen.controller.*.*(..))")
    public void webLog() {}

    /**
     * 日志记录的环绕通知
     */
    @Around("webLog()")
    public Object recordWebLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        WebLog webLog = new WebLog();
        long start = System.currentTimeMillis();
        result = joinPoint.proceed(joinPoint.getArgs());
        long end = System.currentTimeMillis();
        webLog.setSpendTime((int)(end - start) / 1000);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) (RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        webLog.setUri(request.getRequestURI());
        String url = request.getRequestURL().toString();
        webLog.setUrl(url);
        webLog.setBasePath(StrUtil.removeSuffix(url, URLUtil.url(url).getPath()));
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        webLog.setUsername(authentication == null ? "anonymous": authentication.getPrincipal().toString());
        //TODO 获取用户真实IP地址
        webLog.setIp(request.getRemoteAddr());
        String className = joinPoint.getTarget().getClass().getName();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(annotation == null ? "no desc": annotation.value());
        webLog.setMethod(className + "." + method.getName());
        webLog.setParameter(getMethodParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        log.info(JSON.toJSONString(webLog, true));
        return result;
    }

    /**
     * 获取方法的参数
     * @param method    method
     * @param args      args
     * @return          {"key": value}
     */
    private Object getMethodParameter(Method method, Object[] args) {
        Map<String, Object> map = new HashMap<>();
        LocalVariableTableParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
        // 方法的形参名称
        String[] parameterNames = parameterNameDiscoverer.getParameterNames(method);
        for (int i = 0; i < Objects.requireNonNull(parameterNames).length; i++) {
            if ("password".equals(parameterNames[i]) || "file".equals(parameterNames[i])) {
                map.put(parameterNames[i], "受限的支持类型");
            } else {
                map.put(parameterNames[i], args[i]);
            }
        }
        return map;
    }


}
